//
//  NetWorkView.m
//  商城
//
//  Created by runone02 on 2018/9/11.
//  Copyright © 2018年 liqiyun. All rights reserved.
//

#import "NetWorkView.h"
#import "roliingCell.h"
#import "HDNetwork.h"
#import "HDNetwork+RAC.h"
@interface NetWorkView()

@end

@implementation NetWorkView{
    HDCachePolicy cachePolicy;
    HDRequestMethod method;
}
static NSString *const collectionCellId = @"roliingCell";
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
        method = HDRequestMethodGET;
        
        //开启控制台log
        [HDNetwork setLogEnabled:YES];
//        [HDNetwork setBaseURL:@"https://atime.com/app/v1/"];
        //    [HDNetwork setFiltrationCacheKey:@[@"time",@"ts"]];
        [HDNetwork setRequestTimeoutInterval:60.0f];
        
        //按App版本号缓存网络请求内容 可修改版本号查看效果 或 使用自定义版本号方法
        [HDNetwork setCacheVersionEnabled:NO];
        
        //网络状态
        __weak __typeof(&*self)weakSelf = self;
        [HDNetwork getNetworkStatusWithBlock:^(HDNetworkStatusType status) {
            weakSelf.StateLabel.text = [NSString stringWithFormat:@"当前网络:%@",[weakSelf getStateStr:status]];
        }];
        
        //演示请求
        [self request:_requestBtn];
    }
    return self;
}

- (void)setupUI {

    self.StateLabel = [[UILabel alloc]init];
    self.StateLabel.textColor = [UIColor blackColor];
    self.StateLabel.backgroundColor = [UIColor redColor];
    self.StateLabel.font = TITLE_FONT(30);
    self.StateLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:self.StateLabel];
    [self.StateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self);
        make.left.right.mas_equalTo(self);
        make.height.mas_equalTo(30);
    }];
    
    self.StackView = [[UIView alloc]init];
    self.StackView.backgroundColor = [UIColor yellowColor];
    [self addSubview:self.StackView];
    [self.StackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.StateLabel.mas_bottom).with.offset(10);
        make.left.right.mas_equalTo(self);
        make.height.mas_equalTo(30);
    }];
    
    self.responseTextView = [[UITextView alloc]init];
    self.responseTextView.backgroundColor = [UIColor blueColor];
    [self addSubview:self.responseTextView];
    [self.responseTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.StackView.mas_bottom).with.offset(10);
        make.left.right.mas_equalTo(self);
        make.height.mas_equalTo(80);
    }];
    
    self.urlTextField = [[UITextField alloc]init];
    [self addSubview:self.urlTextField];
    [self.urlTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.responseTextView.mas_bottom).with.offset(10);
        make.left.right.mas_equalTo(self);
        make.height.mas_equalTo(50);
    }];
    
    self.requestBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.requestBtn setTitle:@"请求" forState:UIControlStateNormal];
    [self.requestBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.requestBtn.backgroundColor = [UIColor blueColor];
    [self.requestBtn addTarget:self action:@selector(request:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.requestBtn];
    [self.requestBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.responseTextView.mas_bottom).with.offset(10);
        make.left.mas_equalTo(self);
        make.width.mas_equalTo(SCREEN_WIDTH/4);
        make.height.mas_equalTo(50);
    }];
    
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.cancelButton.backgroundColor = [UIColor blueColor];
    [self.cancelButton addTarget:self action:@selector(cancelRequest:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.cancelButton];
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.responseTextView.mas_bottom).with.offset(10);
        make.left.mas_equalTo(self.requestBtn.mas_right);
        make.width.mas_equalTo(SCREEN_WIDTH/4);
        make.height.mas_equalTo(50);
    }];
    
    self.emptyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.emptyBtn setTitle:@"清空" forState:UIControlStateNormal];
    [self.emptyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.emptyBtn.backgroundColor = [UIColor blueColor];
    [self.emptyBtn addTarget:self action:@selector(empty:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.emptyBtn];
    [self.emptyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.responseTextView.mas_bottom).with.offset(10);
        make.left.mas_equalTo(self.cancelButton.mas_right);
        make.width.mas_equalTo(SCREEN_WIDTH/4);
        make.height.mas_equalTo(50);
    }];
    
    
    self.clearRequestBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.clearRequestBtn setTitle:@"清理缓存" forState:UIControlStateNormal];
    [self.clearRequestBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.clearRequestBtn.backgroundColor = [UIColor blueColor];
    [self.clearRequestBtn addTarget:self action:@selector(clearRequest:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.clearRequestBtn];
    [self.clearRequestBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.responseTextView.mas_bottom).with.offset(10);
        make.left.mas_equalTo(self.emptyBtn.mas_right);
        make.width.mas_equalTo(SCREEN_WIDTH/4);
        make.height.mas_equalTo(50);
    }];

}


/**请求*/
- (void)request:(UIButton *)sender {
    sender.enabled = NO;
    __weak __typeof(&*self)weakSelf = self;
    if (HDRequestMethodGET == method) {
        [HDNetwork HTTPGetUrl:_urlTextField.text parameters:nil cachePolicy:cachePolicy callback:^(id responseObject, NSError *error, BOOL isFromCache) {
            sender.enabled = YES;
            if (!error) {
                weakSelf.responseTextView.text = [NSString stringWithFormat:@"%@",responseObject];
            }else{
                weakSelf.responseTextView.text = [error localizedDescription];
                NSLog(@"---->%@",@"错误");
            }
        }];
    }
    else{
        [HDNetwork HTTPUnCacheWithMethod:method url:_urlTextField.text parameters:nil callback:^(id responseObject, NSError *error, BOOL isFromCache) {
            sender.enabled = YES;
            if (!error) {
                weakSelf.responseTextView.text = [NSString stringWithFormat:@"%@",responseObject];
            }else{
                weakSelf.responseTextView.text = [error localizedDescription];
                NSLog(@"---->%@",@"错误");
            }
        }];
    }
}


/**取消请求*/
- (void)cancelRequest:(UIButton *)sender {
    [HDNetwork cancelRequestWithURL:_urlTextField.text];
    _requestBtn.enabled = YES;
}


/**清空*/
- (void)empty:(UIButton *)sender {
    _responseTextView.text = @"";
}

/**清除缓存*/
- (void)clearRequest:(UIButton *)sender {
    sender.enabled = NO;
    [HDNetwork removeAllHttpCacheBlock:nil endBlock:^(BOOL error) {
        //通知主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            sender.enabled = YES;
        });
    }];
}


/**获取网络状态*/
- (NSString *)getStateStr:(HDNetworkStatusType)status{
    switch (status) {
        case HDNetworkStatusUnknown:
            return @"未知网络";
            break;
        case HDNetworkStatusNotReachable:
            return @"无网路";
            break;
        case HDNetworkStatusReachableWWAN:
            return @"手机网络";
            break;
        case HDNetworkStatusReachableWiFi:
            return @"WiFi网络";
            break;
        default:
            break;
    }
}

/**获取网络状态*/
- (NSString *)getCacheStr:(HDCachePolicy)cache{
    switch (cache) {
        case HDCachePolicyIgnoreCache:
            return @"只从网络获取数据，且数据不会缓存在本地";
            break;
        case HDCachePolicyCacheOnly:
            return @"只从缓存读数据，如果缓存没有数据，返回一个空";
            break;
        case HDCachePolicyNetworkOnly:
            return @"先从网络获取数据，同时会在本地缓存数据";
            break;
        case HDCachePolicyCacheElseNetwork:
            return @"先从缓存读取数据，如果没有再从网络获取";
            break;
        case HDCachePolicyNetworkElseCache:
            return @"先从网络获取数据，如果没有再从缓存读取数据，此处的没有可以理解为访问网络失败，再从缓存读取数据";
            break;
        case HDCachePolicyCacheThenNetwork:
            return @"先从缓存读取数据，然后在从网络获取并且缓存，Block将产生两次调用";
            break;
        default:
            break;
    }
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self endEditing:YES];
}
@end
